package com.xebest.web.controller.venmanager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.*;
import com.xebest.api.service.VenProSpuApiService;
import com.xebest.api.service.XeVenInfoShopApiService;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.web.form.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺中心相关接口
 *
 * @author shihui
 */
@Controller
@RequestMapping("/xeveninfoshop")
public class XeVenInfoShopController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(XeVenInfoShopController.class);

    @Autowired
    private XeVenInfoShopApiService xeVenInfoShopApiService;
    @Autowired
    private VenProSpuApiService venProSpuApiService;
    @Autowired
    private Environment env;

    /**
     * 根据userId获取店铺信息
     *
     * @author shihui
     */
    @RequestMapping("/getShopInfo")
    @ResponseBody
    public BaseResponse getShopInfo() {
        log.info("店铺中心--根据userId获取店铺信息--start-- ");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String userCode = userInfo.getString("userCode");
            if (StringUtils.isBlank(userCode)) {
                return sendAjaxError("登录状态异常，userCode为空");
            }
            //封装参数DTO
            ParameterDTO dto = new ParameterDTO();
            dto.setUserCode(userCode);
            XeVenInfoShopResponseDTO returnDto = xeVenInfoShopApiService.getShopInfo(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            //封装from
            XeVenGetShopInfoForm form = new XeVenGetShopInfoForm();
            form.setLoginName(returnDto.getLoginName());
            List<XeVenInfoShopContactsDTO> list = returnDto.getShopContacts();
            List<XeVenInfoShopContactsForm> reslist = new ArrayList<>();
            for (XeVenInfoShopContactsDTO contacts : list) {
                XeVenInfoShopContactsForm contactsForm = JSON.parseObject(
                        JSON.toJSONString(contacts), XeVenInfoShopContactsForm.class);
                reslist.add(contactsForm);
            }
            form.setShopContacts(reslist);
            form.setShopDomain(returnDto.getShopDomain());
            form.setShopId(returnDto.getShopId());
            form.setShopLogo(returnDto.getShopLogo());
            form.setShopSigns(returnDto.getShopSigns());
            form.setShopName(returnDto.getShopName());

            Map<String, Object> res = new HashMap<>();
            res.put("venInfoShop", form);
            res.put("picServer", env.getProperty("erp.imgUrl"));
            return sendAjaxOK(res);
        } catch (Exception e) {
            log.error("店铺中心--根据userId获取店铺信息接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 修改店铺联系人
     *
     * @author shihui
     */
    @RequestMapping("/updateShopContact")
    @ResponseBody
    public BaseResponse updateShopContact(@RequestBody XeVenInfoShopContactsForm form) {
        log.info("店铺中心--修改店铺联系人--start-- :{}", JSONObject.toJSONString(form));
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String userCode = userInfo.getString("userCode");
            if (StringUtils.isBlank(userCode)) {
                return sendAjaxError("登录状态异常，userCode为空");
            }
            //封装参数DTO
            XeVenInfoShopContactsRequestDTO dto = JSON.parseObject(
                    JSON.toJSONString(form), XeVenInfoShopContactsRequestDTO.class);
            dto.setUserCode(userCode);
            dto.setModifyUser(userInfo.getString("loginName"));
            BaseResponseDTO returnDto = xeVenInfoShopApiService.updateShopContact(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("店铺中心--修改店铺联系人接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 店铺概览展示
     *
     * @author shihui
     */
    @RequestMapping("/shopOverview")
    @ResponseBody
    public BaseResponse shopOverview() {
        log.info("店铺中心--店铺概览展示--start-- :");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String userCode = userInfo.getString("userCode");
            if (StringUtils.isBlank(userCode)) {
                return sendAjaxError("登录状态异常，userCode为空");
            }
            //封装参数DTO
            ParameterDTO dto = new ParameterDTO();
            dto.setUserCode(userCode);
            XeVenInfoShopResponseDTO returnDto = xeVenInfoShopApiService.shopOverview(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            //封装form
            XeShopOverviewForm form = new XeShopOverviewForm();
            form.setPullOfPro(returnDto.getPullOfPro());
            form.setRefusePro(returnDto.getRefusePro());
            form.setSalePro(returnDto.getSalePro());
            form.setShopId(returnDto.getShopId());
            form.setShopLogo(returnDto.getShopLogo());
            form.setVenName(returnDto.getVenName());
            //结果返回
            Map<String, Object> res = new HashMap<>();
            res.put("venInfoShop", form);
            res.put("picServer", env.getProperty("erp.imgUrl"));
            return sendAjaxOK(res);
        } catch (Exception e) {
            log.error("店铺中心--店铺概览展示接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 店铺信息修改
     *
     * @author shihui
     */
    @RequestMapping("/updateShopInfo")
    @ResponseBody
    public BaseResponse updateShopInfo(@RequestBody XeVenInfoShopForm xeVenInfoShopForm) {
        log.info("店铺中心--店铺信息修改--start-- :{}", JSONObject.toJSONString(xeVenInfoShopForm));
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String shopId = xeVenInfoShopForm.getShopId();
            if (StringUtils.isBlank(shopId)) {
                return sendAjaxError("shopId不能为空");
            }
            //封装参数DTO
            XeVenInfoShopRequestDTO dto = new XeVenInfoShopRequestDTO();
            dto.setShopId(shopId);
            dto.setShopLogo(xeVenInfoShopForm.getShopLogo());
            dto.setShopSigns(xeVenInfoShopForm.getShopSigns());
            dto.setComDesc(xeVenInfoShopForm.getComDesc());
            dto.setModifyUser(userInfo.getString("loginName"));
            dto.setUserCode(userInfo.getString("userCode"));
            BaseResponseDTO returnDto = xeVenInfoShopApiService.updateShopInfo(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("店铺中心--店铺信息修改接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 商家信息展示
     *
     * @author shihui
     */
    @RequestMapping("/showShopInfo")
    @ResponseBody
    public BaseResponse showShopInfo() {
        log.info("店铺中心--商家信息展示--start-- :{}");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String userCode = userInfo.getString("userCode");
            if (StringUtils.isBlank(userCode)) {
                return sendAjaxError("登录状态异常，userCode为空");
            }
            //封装参数DTO
            ParameterDTO dto = new ParameterDTO();
            dto.setUserCode(userCode);
            XeVenInfoShopResponseDTO returnDto = xeVenInfoShopApiService.showShopInfo(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            XeVenInfoShopForm form = JSON.parseObject(
                    JSON.toJSONString(returnDto), XeVenInfoShopForm.class);
            Map<String, Object> res = new HashMap<>();
            res.put("venInfoShop", form);
            res.put("picServer", env.getProperty("erp.imgUrl"));
            return sendAjaxOK(res);
        } catch (Exception e) {
            log.error("店铺中心--商家信息展示接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 修改商家信息
     *
     * @author shihui
     */
    @RequestMapping("/updateVenInfo")
    @ResponseBody
    public BaseResponse updateVenInfo(@RequestBody UpdateShopParamForm xeVenInfoShopForm) {
        log.info("店铺中心--修改商家信息--start-- :{}");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            if (xeVenInfoShopForm.getAreaId() == null) {
                return sendAjaxError("商品销售区域不能为空");
            }
            String userCode = userInfo.getString("userCode");
            if (StringUtils.isBlank(userCode)) {
                return sendAjaxError("登录状态异常，userCode为空");
            }
            //封装参数DTO
            UpdateShopParamDTO dto = new UpdateShopParamDTO();
            dto.setAreaId(xeVenInfoShopForm.getAreaId());
            dto.setBusinessType(xeVenInfoShopForm.getBusinessType());
            String businessType = xeVenInfoShopForm.getBusinessType();
            String[] businessTypeId = businessType.split(",");
            StringBuilder businessTypeName = new StringBuilder();
            for (int i = 0; i < businessTypeId.length; i++) {
                businessTypeName.append(XeBaseUtil.baseUtil.getCategoryName(businessTypeId[i]));
                if (i != businessTypeId.length - 1) {
                    businessTypeName.append(",");
                }
            }
            dto.setBusinessTypeName(businessTypeName.toString());
            dto.setCityId(xeVenInfoShopForm.getCityId());
            dto.setComEstabDate(xeVenInfoShopForm.getComEstabDate());
            dto.setComPhone(xeVenInfoShopForm.getComPhone());
            dto.setProvinceId(xeVenInfoShopForm.getProvinceId());
            dto.setRegistCapital(xeVenInfoShopForm.getRegistCapital());
            dto.setShopId(xeVenInfoShopForm.getShopId());
            dto.setVenAddr(xeVenInfoShopForm.getVenAddr());
            dto.setUserCode(userCode);
            BaseResponseDTO returnDto = xeVenInfoShopApiService.updateVenInfo(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("店铺中心--商家信息展示接口异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 判断销售区域是否可删除
     *
     * @author shihui
     */
    @RequestMapping("/checkSpuByArea")
    @ResponseBody
    public BaseResponse checkSpuByArea(HttpServletRequest req) {
        log.info("店铺中心--修改商家信息--start-- :{}");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            JSONObject obj = requstPayloadToJson(req);
            Integer areaId = obj.getInteger("areaId");
            if (areaId == null) {
                return sendAjaxError("areaId不能为空");
            }
            ParameterProDTO dto = new ParameterProDTO();
            dto.setAreaId(areaId);
            dto.setUserCode(userInfo.getString("userCode"));
            BaseResponseDTO returnDto = venProSpuApiService.checkSpuByArea(dto);
            if (!"2000".equals(returnDto.getStatus())) {
                return sendAjaxError(returnDto.getMsg());
            }
            if ("n".equals(returnDto.getMsg())) {
                return sendRemoteAjaxError("该区域下有可销售的商品，不可删除");
            }
            return sendRemoteAjaxOK();
        } catch (Exception e) {
            log.error("店铺中心--商家信息展示接口异常:{}", e);
            return sendAjaxError();
        }
    }

}
